// pages/operation/clueManage/addClue/index.js
import formRules from "../../../../utils/rules-form.js";
import { CommonModel } from "../../../../api/api-common/commonModel.js";
import { ClueModel } from "../../../../api/api-work/clueModel.js";
import { timestampToTime } from "../../../../utils/index.js";
const clueModel = new ClueModel();
const commonModel = new CommonModel();
const rules = {
  name: [
    {
      required: true,
      message: "请输入学员姓名",
    },
  ],
  mobile: [
    {
      required: true,
      message: "请输入手机号码",
    },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入有效的手机号(11位数字,以1开头,第二位是3到9之间的数字)",
      trigger: "blur",
    },
  ],
};
Page({
  /**
   * 页面的初始数据
   */

  data: {
    userInfo: {}, // 编辑学员带过来的信息
    name: "", // 学员姓名
    familyRel: "无", // 家长
    mobile: "", // 家长手机号
    gender: "2", // "0" 男； "1": 女；"2": 未知
    birthdayValue: "",
    birthday: "", // 出生日期
    attendSchool: "", // 就读学校
    gradeName: "", // 当年年级
    gradeNameText: "", // 当前年级显示
    backFamilyRel: "无", // 备用家长
    phone: "", // 备用手机号
    joinWay: "", // 学员来源
    joinWayName: "", // 学员来源显示
    creator: "", // 学员创建人
    creatorName: "", // 学员创建人显示
    remark: "", // 备注

    isBackFamily: false, // 是否点击备用家长，默认false
    sexDatas: [], // 性别集合
    isShowBirth: false, // 显示出生日期
    minBirth: new Date(1990, 0, 1).getTime(),
    isShowGrade: false, // 显示年级选择
    gradeList: [],
    isShowFamily: false, // 是否显示家长弹窗
    familyShowDatas: [
      {
        label: "无",
        value: "无",
      },
      {
        label: "妈妈",
        value: "妈妈",
      },
      {
        label: "爸爸",
        value: "爸爸",
      },
      {
        label: "本人",
        value: "本人",
      },
      {
        label: "爷爷",
        value: "爷爷",
      },
      {
        label: "奶奶",
        value: "奶奶",
      },
      {
        label: "外公",
        value: "外公",
      },
      {
        label: "外婆",
        value: "外婆",
      },
    ],
    yixiang: "0",
    isShowStudent: false, // 学员来源
    studentSourceList: [], // 学生来源
    isShowPeople: false, // 学员创建人
    peopleList: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    if (options.param) {
      wx.setNavigationBarTitle({
        title: "编辑资料",
      });

      const userInfo = JSON.parse(options.param);
      console.log("userInfo: ", userInfo);
      // return;
      this.setData({
        userInfo: userInfo,
        name: userInfo.name,
        familyRel: userInfo.defaultUser && userInfo.defaultUser.familyRel,
        mobile: userInfo.defaultUser && userInfo.defaultUser.mobile,
        gender: userInfo.gender + "",
        birthday: userInfo.birthday == null ? "" : userInfo.birthday,
        birthdayValue: new Date(userInfo.birthday).getTime(),
        attendSchool:
          userInfo.attendSchool == null ? "" : userInfo.attendSchool,
        gradeName: userInfo.gradeId == null ? "" : userInfo.gradeId,
        gradeNameText: userInfo.gradeName == null ? "" : userInfo.gradeName,
        backFamilyRel:
          userInfo.backupUser == null
            ? "无"
            : userInfo.backupUser.familyRel == null
            ? ""
            : userInfo.backupUser.familyRel,
        phone: userInfo.backupUser && userInfo.backupUser.mobile,
        joinWay: userInfo.joinWay == null ? "" : userInfo.joinWay,
        joinWayName: userInfo.joinName == null ? "" : userInfo.joinName,
        creator: userInfo.creator,
        creatorName: userInfo.creatName,
        remark: userInfo.remark,
      });
    }
    // 获取性别
    await this.getSexType();
    // 获取年级
    await this.getGradeDatas();
    // 获取学生来源
    await this.getStudentData();
    // 获取学员创建人
    await this.getPeopleData();
  },

  // 获取性别
  getSexType() {
    commonModel
      .getDictTypeDataApi({
        dictType: "sys_user_sex",
      })
      .then((res) => {
        this.setData({
          sexDatas: res,
        });
      });
  },

  // 获取学生来源
  async getStudentData() {
    clueModel.getStudentSourceApi().then((res) => {
      console.log("res: ", res);
      this.setData({
        studentSourceList: res,
      });
    });
  },

  // 获取学员创建人
  async getPeopleData() {
    clueModel
      .getPeopleListApi({
        pageNum: 1,
        pageSize: 999,
      })
      .then((res) => {
        this.setData({
          peopleList: res.rows,
        });
      });
  },

  // 选择出生日期
  showBirthPopup() {
    this.setData({
      isShowBirth: true,
    });
  },

  // 选中出生日期
  selectBirth(e) {
    this.setData({
      birthdayValue: e.detail,
      birthday: timestampToTime(e.detail),
      isShowBirth: false,
    });
  },

  // 关闭出生日期
  onCloseBirth() {
    this.setData({
      isShowBirth: false,
    });
  },

  // 显示主家长弹窗
  showFamilyMainPopup() {
    this.setData({
      isShowFamily: true,
      isBackFamily: false, // 主家长
    });
  },

  // 显示备用家长弹窗
  showFamilyBackPopup() {
    this.setData({
      isShowFamily: true,
      isBackFamily: true, // 备用家长
    });
  },

  // 选择家长
  selectFamily(e) {
    const item = e.currentTarget.dataset.query;
    if (this.data.isBackFamily == false) {
      // 主家长
      this.setData({
        familyRel: item.value,
        isShowFamily: false,
      });
    } else {
      // 备用家长
      this.setData({
        backFamilyRel: item.value,
        isShowFamily: false,
      });
    }
  },

  // 关闭家长弹窗
  onCloseFamily() {
    this.setData({
      isShowFamily: false,
    });
  },

  // 获取年级
  async getGradeDatas() {
    clueModel.getGrageListApi().then((res) => {
      this.setData({
        gradeList: res,
      });
    });
  },

  // 显示学员创建人
  showPeoplePopup() {
    this.setData({
      isShowPeople: true,
    });
  },

  // 选择创建人
  selectPeople(e) {
    const query = e.currentTarget.dataset.query;
    this.setData({
      isShowPeople: false,
      creator: query.id,
      creatorName: query.nickName,
    });
  },

  // 关闭创建人显示
  onClosePeople() {
    this.setData({
      isShowPeople: false,
    });
  },

  // 显示年级弹窗
  showGradePopup() {
    this.setData({
      isShowGrade: true,
    });
  },

  // 选择年级
  selectGrage(e) {
    const query = e.currentTarget.dataset.query;
    this.setData({
      isShowGrade: false,
      gradeName: query.value,
      gradeNameText: query.label,
    });
  },

  // 关闭年级显示
  onCloseGrade() {
    this.setData({
      isShowGrade: false,
    });
  },

  // 学员来源弹窗
  showStudentPopup() {
    this.setData({
      isShowStudent: true,
    });
  },

  // 选择学员来源
  selectStudent(e) {
    const query = e.currentTarget.dataset.query;
    console.log("学员来源: ", query);
    this.setData({
      isShowStudent: false,
      joinWay: query.dictValue,
      joinWayName: query.dictLabel,
    });
  },

  // 关闭学员来源弹窗
  onCloseStudent() {
    this.setData({
      isShowStudent: false,
    });
  },

  // 完成
  finishClue() {
    const param = {
      name: this.data.name,
      defaultUser: {
        mobile: this.data.mobile,
        familyRel: this.data.familyRel,
      },
      gender: this.data.gender,
      birthday: this.data.birthday,
      attendSchool: this.data.attendSchool,
      gradeName: this.data.gradeName,
      backupUser: {
        mobile: this.data.phone,
        familyRel: this.data.backFamilyRel,
      },
      joinWay: this.data.joinWay,
      creator: this.data.creator,
      remark: this.data.remark,
    };
    if (this.data.userInfo) {
      // 编辑
      param["id"] = this.data.userInfo.id;
    }
    formRules(rules, this.data, (status) => {
      if (status) {
        clueModel.getSaveClueApi(param).then((res) => {
          wx.navigateBack({
            delta: 1,
            // complete: _ => {
            //   this.setData({ backFlag: true })
            // }
          });
        });
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
});
